import React from 'react';
import { createModalContainer } from '../../../components/changeModal';
import {Button,Form , Icon, message, Spin} from 'antd';
import styles from './index.less';
import SelectedImage from '@/components/plugins/selectImage/index';
import InputText from '@/components/Input/index';
import { connect } from 'dva';
const FormItem = Form.Item;

@Form.create()
class Component extends React.Component {
  constructor(props) {
      super(props);
      this.state = {
        imageUrl: '',
        name: '',
        isFetching: false,
      }
  }

  componentWillMount() {
      this.GetFirstGroupById(this.props.param.firstId);
      window.Isoption = false;
  }

  componentDidMount() {
    window.Isoption = true;
  }

  // 获取一级
  GetFirstGroupById = id => {
    const { dispatch} = this.props;
    dispatch({
        type: 'productClassify/GetFirstGroupById',
        payload: {
            id: id
        },
        callBack: {
            success: (res) => {
                this.setState({
                    imageUrl: res.Data.Banner,
                    width: res.Data.Width,
                    height: res.Data.Height,
                    name: res.Data.Name
                })
            }
        }
    });
 }

  // 图片插件
  imgModal = ref => {
    this.imgmodal = ref;
  };
  OpenImageModal = () => {
    this.imgmodal.handleShowModal();
  };
  onImageChange = res => {
    this.setState({
      imageUrl: res.imageUrl.substr(res.imageUrl.indexOf('.com/') + 5),
      width: res.width,
      height: res.height
    });
    this.imgmodal.handleModalVisible();
  };

    //取消
    handleCancel =() => {
    this.props.cancel();
    }

    onTextChange = (v) => {
        this.setState({ name: v.target.value  });
    }

     // 提交
    handleSubmit =e => {
        e.preventDefault();
        const { dispatch } = this.props;
        const id = this.props.param.firstId;
        const {imageUrl, width, height} = this.state;        
        this.props.form.validateFields(async (err, values) =>{
        const name = values.name;
        if(!err) {
            dispatch({
                type: 'productClassify/UpdateFirstGroup',
                payload: {
                    id: id,
                    name: name,
                    imgPath: imageUrl,
                    width: width,
                    height: height,
                },
                callBack: {
                    success: res => {
                        if(res.Code === 0) {
                            message.success('修改成功');
                            this.props.ok();
                        }
                    },
                    error: res => {
                        message.error(res.Msg);
                    },
                }
            })       
        }})
    }

    render() {
      const {getFieldDecorator} = this.props.form;
      const {oemInfo, loading, btnLoading} = this.props;
      const formItemLayout = {
        labelCol: {
          span: 6 ,
        },
        wrapperCol: {
          span: 8 ,
        },
      };
      const dataName = this.state.name;
        return (
            <div style={{marginTop: 24}}>
                <SelectedImage onRef={this.imgModal} selectImage={this.onImageChange} />
                <Spin spinning={loading}>
                <Form onSubmit={this.handleSubmit}>
                    <FormItem label="分类名称" {...formItemLayout}>
                        {getFieldDecorator('name', {
                            initialValue: dataName,
                            rules: [
                                {required: true, message: '分类名不能为空，最多6个字'},
                                {pattern: /^.{1,6}$/, message: '分类名不能为空，最多6个字'}
                            ],
                            validateTrigger: 'onBlur',
                        })(
                            <InputText name="name" onChange={this.onTextChange}  showtotal maxLength={6} autoFocus/>
                        )}
                    </FormItem>
                    <FormItem label="banner图" className={styles.coverBox} {...formItemLayout}>
                        {getFieldDecorator('url', {
                            rules: [
                                {required: false, message: '分类图不能为空'},
                            ]
                        })(
                            <div className={styles.uploadCover} onClick={this.OpenImageModal}>
                                {this.state.imageUrl ? (
                                    <img src={oemInfo &&oemInfo['cdnUrl'] + '/' + this.state.imageUrl+'?x-oss-process=style/240'}
                                         style={{ width: '100%', height: '100%' }}
                                    />
                                ) : (
                                    <Icon type="plus" />
                                )}
                            </div>
                        )}
                        <div style={{lineHeight: '16px', height: '16px'}}>建议尺寸850*410像素</div>
                    </FormItem>
                    <FormItem className={styles.footBtn}>
                        <Button onClick={this.handleCancel} style={{marginRight: 16}}>
                            取消
                        </Button>
                        <Button
                            type="primary"
                            htmlType="submit"
                            loading={btnLoading}
                        >
                            保存
                        </Button>
                    </FormItem>
                </Form>
                </Spin>
           </div>
        )
    }
}

const OneTypeEdit = createModalContainer(
    connect(({productClassify, global, loading}) => ({
        productFirstGroup: productClassify.productFirstGroup,
        oemInfo: global.oemInfo,
        loading: loading.effects['productClassify/GetFirstGroupById'],
        btnLoading: loading.effects['productClassify/UpdateFirstGroup'],
    }))(Component),
    true,
    true
);

export default OneTypeEdit;